<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="合作商家" prop="partnerShopIds">
        <ShopShowcase
          v-model="formData.partnerShopIds"
          :limit="10"
          placeholder="选择合作商家"
          @change="handlePartnerShopChange"
        />
        <el-text type="info"
          ><span class="ml-5px"
            >前提是线下已经达成合作，且都已入驻平台，此处选择帮送赠品的商家。</span
          ></el-text
        >
      </el-form-item>
      <el-form-item label="赠品来源" prop="spuSource">
        <el-radio-group v-model="spuSource" :disabled="Boolean(formData.id)">
          <el-radio :value="0"> 直接输入</el-radio>
          <el-radio :value="1"> 选择已有产品</el-radio>
          <el-radio :value="2"> 选择优惠券</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="spuSource === 1" label="选择产品" prop="spuId">
        <SpuShowcase v-model="formData.spuId" :limit="1" @change="handleSpuChange" />
      </el-form-item>
      <el-form-item v-if="spuSource === 1" label="选择规格" prop="skuId">
        <div class="h-60px w-60px cursor-pointer" @click="handleSelectSku">
          <div
            v-if="skuData && skuData.picUrl"
            class="select-box"
            :title="skuData.name || skuData.propertiesValue"
          >
            <el-image :src="skuData.picUrl" />
          </div>
          <div v-else class="select-box" title="选择规格">
            <Icon icon="ep:plus" />
          </div>
        </div>
      </el-form-item>
      <el-form-item v-if="spuSource === 2" label="选择优惠券" prop="couponTemplateId">
        <div
          class="h-60px w-60px cursor-pointer"
          @click="openCouponTemplateSelect"
          :title="couponTemplateData.name"
        >
          <div v-if="couponTemplateData && couponTemplateData.id" class="select-box">
            <el-text type="primary">已选择</el-text>
          </div>
          <div v-else class="select-box" title="选择优惠券">
            <el-text type="primary">请选择</el-text>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="赠品名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入赠品名称，如：价值58元的江团烤鱼1条"
          class="!w-240px"
          clearable
        />
      </el-form-item>
      <el-form-item label="生效时间" prop="startTime">
        <el-date-picker
          v-model="formData.startTime"
          type="datetime"
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择生效时间"
          clearable
        />
      </el-form-item>
      <el-form-item label="作废时间" prop="endTime">
        <el-date-picker
          v-model="formData.endTime"
          type="datetime"
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择作废时间"
          clearable
        />
      </el-form-item>
      <el-form-item v-if="spuSource === 0 || spuSource === 1" label="赠品图片" prop="picUrl">
        <UploadImg v-model="formData.picUrl" height="80px" />
      </el-form-item>
      <el-form-item v-if="spuSource === 0 || spuSource === 1" label="原价" prop="originPrice">
        <el-input-number
          v-model="computedOriginPrice"
          maxlength="8"
          :min="0"
          :max="99999999"
          :step="1"
          :precision="2"
          placeholder="请输入原价，0表示免费"
          class="!w-240px"
          clearable
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input-number>
      </el-form-item>
      <el-form-item v-if="spuSource === 0 || spuSource === 1" label="成本" prop="costPrice">
        <el-input-number
          v-model="computedCostPrice"
          maxlength="8"
          :min="0"
          :max="99999999"
          :step="1"
          :precision="2"
          placeholder="请输入成本，0表示免费"
          class="!w-240px"
          clearable
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input-number>
        <el-text type="info"
          ><span class="ml-5px"
            >若成本大于
            0，则线下核销的赠品需支付相应的成本金额，线上发货的赠品需分账相应的成本金额。</span
          ></el-text
        >
      </el-form-item>
      <el-form-item v-if="spuSource === 0 || spuSource === 1" label="库存" prop="stock">
        <el-input-number
          v-model="formData.stock"
          type="number"
          maxlength="8"
          :min="0"
          :max="99999999"
          :step="1"
          :precision="0"
          placeholder="请输入库存"
          class="!w-240px"
          clearable
        />
      </el-form-item>
      <el-form-item label="无限领取">
        <el-switch v-model="computedNoTakeLimit" />
      </el-form-item>
      <el-form-item v-if="!computedNoTakeLimit" label="限领数量" prop="takeLimitCount">
        <el-input-number
          v-model="formData.takeLimitCount"
          type="number"
          maxlength="8"
          :min="-1"
          :max="100"
          :step="1"
          :precision="0"
          placeholder="请输入限领数量"
          :disabled="spuSource === 2"
          class="!w-240px"
          clearable
        />
      </el-form-item>
      <el-form-item v-if="spuSource === 0" label="赠品单位" prop="unit">
        <el-input
          v-model="formData.unit"
          placeholder="请输入赠品单位，如：件、条、瓶"
          maxlength="8"
          class="!w-240px"
          clearable
        />
      </el-form-item>
      <el-form-item label="使用规则" prop="note">
        <el-input
          v-model="formData.note"
          type="textarea"
          :rows="3"
          placeholder="请输入使用规则，如：仅限本人使用、解释权归合作商家"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
  <SkuTableSelect ref="skuTableSelectRef" @change="handleSkuChange" />
  <CouponSelect ref="couponSelectRef" :takeType="4" @change="handleSelectCouponTemplate" />
</template>
<script setup lang="ts">
import * as GiftActivityApi from '@/api/mall/promotion/gift/activity'
import * as ProductSpuApi from '@/api/mall/product/spu'
import * as CouponTemplateApi from '@/api/mall/promotion/coupon/couponTemplate'
import ShopShowcase from '@/views/mall/shop/info/components/ShopShowcase.vue'
import SpuShowcase from '@/views/mall/product/spu/components/SpuShowcase.vue'
import SkuTableSelect from '@/views/mall/product/spu/components/SkuTableSelect.vue'
import { CouponSelect } from '@/views/mall/promotion/coupon/components'
import { fenToYuan, yuanToFen } from '@/utils'

defineOptions({ name: 'GiftActivityForm' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const spuSource = ref(0)
const formLoading = ref(false)
const formType = ref('')
const formData = ref<any>({
  id: undefined,
  partnerShopIds: [],
  name: undefined,
  picUrl: undefined,
  startTime: undefined,
  endTime: undefined,
  originPrice: 0,
  costPrice: 0,
  stock: 99999,
  takeLimitCount: 1,
  unit: '件',
  note: '最终解释权归合作商家',
  spuId: undefined,
  skuId: undefined,
  couponTemplateId: undefined
})
const computedNoTakeLimit = computed({
  get() {
    return formData.value.takeLimitCount < 0 || formData.value.takeLimitCount >= 99999
  },
  set(val: boolean) {
    formData.value.takeLimitCount = val ? -1 : 1
  }
})
const formRules = reactive({
  partnerShopIds: [{ required: true, message: '请选择合作商家', trigger: ['blur', 'change'] }],
  spuSource: [
    {
      required: true,
      validator: (_rule: any, _value: any, callback: any) => {
        if (isNaN(Number(spuSource.value))) {
          callback(new Error('请选择赠品来源'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  spuId: [
    {
      required: true,
      validator: (_rule: any, _value: any, callback: any) => {
        if (spuSource.value !== 1) {
          callback()
          return
        }
        if (!Boolean(formData.value.spuId)) {
          callback(new Error('请选择产品'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  skuId: [
    {
      required: true,
      validator: (_rule: any, _value: any, callback: any) => {
        if (spuSource.value !== 1) {
          callback()
          return
        }
        if (!Boolean(formData.value.skuId)) {
          callback(new Error('请选择产品规格'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  couponTemplateId: [
    {
      required: true,
      validator: (_rule: any, _value: any, callback: any) => {
        if (spuSource.value !== 2) {
          callback()
          return
        }
        if (!Boolean(formData.value.couponTemplateId)) {
          callback(new Error('请选择优惠券'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  name: [{ required: true, message: '赠品名称不能为空', trigger: ['blur', 'change'] }],
  startTime: [{ required: true, message: '生效时间不能为空', trigger: ['blur', 'change'] }],
  endTime: [{ required: true, message: '作废时间不能为空', trigger: ['blur', 'change'] }]
})
const formRef = ref()

const open = async (type: string, id?: number | string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      formData.value = await GiftActivityApi.getDetailById(id)
      if (formData.value.couponTemplateId && Number(formData.value.couponTemplateId) !== 0) {
        spuSource.value = 2
        couponTemplateData.value = await CouponTemplateApi.getCouponTemplate(
          formData.value.couponTemplateId
        )
      } else if (formData.value.spuId && Number(formData.value.spuId) !== 0) {
        spuSource.value = 1
        const spu = await ProductSpuApi.getSpu(formData.value.spuId)
        for (const sku of spu.skus!) {
          if (sku.id == formData.value.skuId) {
            skuData.value = sku
            break
          }
        }
      } else {
        spuSource.value = 0
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

const emit = defineEmits(['success'])
const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  formLoading.value = true
  try {
    const data = formData.value
    if (spuSource.value === 0) {
      // 直接输入赠品，则不关联产品
      data.spuId = undefined
      data.skuId = undefined
    }
    if (formType.value === 'create') {
      await GiftActivityApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await GiftActivityApi.updateById(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    partnerShopIds: [],
    name: undefined,
    picUrl: undefined,
    startTime: undefined,
    endTime: undefined,
    originPrice: 0,
    costPrice: 0,
    stock: 99999,
    takeLimitCount: 1,
    unit: '',
    note: undefined,
    spuId: undefined,
    skuId: undefined,
    couponTemplateId: undefined
  }
  formRef.value?.resetFields()
  skuData.value = {
    id: 0,
    name: '',
    picUrl: '',
    propertiesValue: ''
  }
}

const handlePartnerShopChange = async (_partnerShopIds: any) => {
  await formRef.value.validateField('partnerShopIds')
}

const handleSpuChange = async (spu: ProductSpuApi.Spu) => {
  console.debug(JSON.stringify(spu))
  if (!spu || !spu.id) {
    skuData.value = null
    return
  }
  formData.value.spuId = spu.id
  formData.value.name = spu.name
  formData.value.picUrl = spu.picUrl
  formData.value.originPrice = spu.price
  formData.value.costPrice = spu.costPrice
  formData.value.stock = spu.stock
}

const skuData = ref<any>({})
const skuTableSelectRef = ref()
const handleSelectSku = () => {
  if (!formData.value?.spuId) {
    message.error('请先选择产品')
    return
  }
  skuTableSelectRef.value?.open(formData.value?.spuId)
}
const handleSkuChange = async (sku: ProductSpuApi.Sku) => {
  console.debug(JSON.stringify(sku))
  skuData.value = sku
  if (!sku || !sku.id) {
    return
  }
  formData.value.skuId = sku.id
  formData.value.originPrice = sku.price
  formData.value.costPrice = sku.costPrice
  formData.value.stock = sku.stock
  if (sku.name && sku.name.length && sku.name != '默认') {
    formData.value.name += ' ' + sku.name
  }
  if (sku.picUrl && sku.picUrl.length) {
    formData.value.picUrl = sku.picUrl
  }
}

const computedOriginPrice = computed({
  get: () => Number(fenToYuan(formData.value.originPrice)),
  set: (newValue: number) => {
    formData.value.originPrice = yuanToFen(newValue)
  }
})
const computedCostPrice = computed({
  get: () => Number(fenToYuan(formData.value.costPrice)),
  set: (newValue: number) => {
    formData.value.costPrice = yuanToFen(newValue)
  }
})

const couponSelectRef = ref()
const couponTemplateData = ref<any>({})
const openCouponTemplateSelect = () => {
  couponSelectRef.value?.open()
}
const handleSelectCouponTemplate = (e) => {
  //console.log(JSON.stringify(e))
  if (e && e.length != 1) {
    message.error('只能选择一张优惠券')
    return
  }
  couponTemplateData.value = e[0]
  formData.value.couponTemplateId = couponTemplateData.value.id
  formData.value.name = couponTemplateData.value.name
  formData.value.takeLimitCount = Math.max(-1, couponTemplateData.value.takeLimitCount)
  formData.value.unit = '张'
  formData.value.note = couponTemplateData.value.description
  if (couponTemplateData.value.validityType == 1) {
    formData.value.startTime = couponTemplateData.value.validStartTime
    formData.value.endTime = couponTemplateData.value.validEndTime
  } else {
    const now = new Date().getTime()
    formData.value.startTime = now + couponTemplateData.value.fixedStartTerm * 24 * 60 * 60 * 1000
    formData.value.endTime = now + couponTemplateData.value.fixedEndTerm * 24 * 60 * 60 * 1000
    formData.value.note +=
      '领取之后第' +
      couponTemplateData.value.fixedStartTerm +
      '至' +
      couponTemplateData.value.fixedEndTerm +
      '天有效。'
  }
}
</script>
